/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/
#include <QBrush>
#include <QFontMetrics>
#include <QDebug>
#include <QDate>

#include "querymodel.h"
#include "query.h"

namespace SQL
{

QueryModel::QueryModel(Query *parent, const QStringList & columns, const QStringList & columnNames)
		: QAbstractTableModel(parent), m_parent(parent)
{
	m_columns = columns;
	setColumnNames(columnNames);
	connect(parent, SIGNAL(afterSelect()), SLOT(afterSelect()));
	connect(parent, SIGNAL(afterClose()), SLOT(afterSelect()));
	connect(parent, SIGNAL(afterPost()), SLOT(afterSelect()));
	connect(parent, SIGNAL(afterCancel()), SLOT(afterSelect()));
}

void QueryModel::afterSelect()
{
	m_checkedRows.clear();
	m_checkedRows.resize( rowCount() );
	m_checkedRows.fill( false );
	reset();
}

int QueryModel::rowCount(const QModelIndex & /*parent*/) const
{
	return m_parent->result().size();
}

int QueryModel::columnCount(const QModelIndex & /*parent*/) const
{
	return m_columns.size();
}

QVariant QueryModel::data(const QModelIndex & index, int role) const
{
	QVariant ret;

	switch (role)
	{
		case Qt::EditRole:
		case Qt::DisplayRole:
		case Qt::ToolTipRole:
			ret = m_parent->result()[index.row()].value(m_columns[index.column()]);
			break;

		case Qt::TextAlignmentRole:
			ret = Query::typeIsNumber(m_parent->result()[index.row()].value(m_columns[index.column()]).type()) ? (int)(Qt::AlignRight | Qt::AlignVCenter) : (int)(Qt::AlignLeft | Qt::AlignVCenter);
			break;

		case Qt::WhatsThisRole:
			ret = qVariantFromValue(reinterpret_cast<QObject*>(m_parent));
			break;
		case Qt::CheckStateRole:
			if (m_columns.indexOf( m_checkableColumn ) == index.column())
				ret = m_checkedRows[index.row()]?Qt::Checked:Qt::Unchecked;
			break;
		default:
			break;
                case Qt::TextColorRole:
                 // case Qt::BackgroundRole:
                        try
                        {
                            if(     (QDate(m_parent->result()[index.row()].value(m_columns[m_columns.size()-1]).toDate())
                                     == QDate::currentDate()
                                    )
                                   &&
                                    (QDate(m_parent->result()[index.row()].value(m_columns[m_columns.size()-2]).toDate())
                                      != QDate::currentDate()
                                     )
                                )
                                ret = qVariantFromValue(QColor(Qt::blue));
                            else
                                if(QDate(m_parent->result()[index.row()].value(m_columns[m_columns.size()-2]).toDate())
                                         == QDate::currentDate()
                                    )
                                    ret = qVariantFromValue(QColor(Qt::red));

                        }
                        catch(...){}
                        break;
	}
	return ret;
}

bool QueryModel::setData ( const QModelIndex & index, const QVariant & value, int role)
{
	if (role!=Qt::CheckStateRole || m_columns.indexOf( m_checkableColumn ) != index.column())
		return false;
	m_checkedRows[index.row()]=(Qt::Checked==value.toInt());
	return true;
}

void QueryModel::setColumns(const QStringList & columns)
{
	m_columns = columns;
	afterSelect();
}

void QueryModel::setColumnNames(const QStringList & columnNames)
{
	m_columnNames = columnNames;
}

QVariant QueryModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	QVariant ret;
	switch (role)
	{
		case Qt::EditRole:
		case Qt::DisplayRole:
		case Qt::ToolTipRole:
			if (orientation == Qt::Horizontal)
			{
				if (section < m_columnNames.size())
					ret=m_columnNames[section];
			}
			else
				ret=section + 1;
			break;
}
	return ret;
}

void QueryModel::setCheckableColumn(const QString& checkableColumn)
{
	m_checkableColumn=checkableColumn;
	afterSelect();
}

void QueryModel::checkAll()
{
	emit(layoutAboutToBeChanged());
	m_checkedRows.fill( true );
	emit(layoutChanged());
}

void QueryModel::uncheckAll()
{
	emit(layoutAboutToBeChanged());
	m_checkedRows.fill( false );
	emit(layoutChanged());
}
const QVector<bool> & QueryModel::checkedRows()
{
	return m_checkedRows;
}

Qt::ItemFlags QueryModel::flags(const QModelIndex & index) const
{
	Q_UNUSED(index);

	if (m_parent->state() == Query::Select)
		return Qt::ItemIsSelectable | Qt::ItemIsEnabled | (Qt::ItemFlags)((m_columns.indexOf( m_checkableColumn )==index.column())?Qt::ItemIsUserCheckable:0);
	else
		return Qt::NoItemFlags;
}

void QueryModel::setView(TableView *view)
{
    m_view =  view;
}

void QueryModel::sort ( int column, Qt::SortOrder order )
{    
    m_parent->sort(m_view->fields().at(column), order);
    reset();
}

QueryModel::~QueryModel()
{
}

}
